package aiku.numericalcontroloa.Service.OrderManagement.Impl;

import aiku.numericalcontroloa.Base.Utils.BaseEnum;
import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import aiku.numericalcontroloa.Mapper.*;
import aiku.numericalcontroloa.Mapper.FinanceManagement.AccountMapper;
import aiku.numericalcontroloa.Mapper.FinanceManagement.IncomeExpenditureDetailMapper;
import aiku.numericalcontroloa.Mapper.MasterControl.MessageNotificationMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderBillingMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderCommissionMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderGoodsMapper;
import aiku.numericalcontroloa.Mapper.OrderManagement.OrderMapper;
import aiku.numericalcontroloa.Model.Dto.OrderManagement.OrderBillingDto;
import aiku.numericalcontroloa.Model.Dto.OrderManagement.OrderDto;
import aiku.numericalcontroloa.Model.Dto.OrderManagement.RoyaltyDto;
import aiku.numericalcontroloa.Model.Entity.*;
import aiku.numericalcontroloa.Model.Entity.FinanceManagement.Account;
import aiku.numericalcontroloa.Model.Entity.FinanceManagement.IncomeExpenditureDetail;
import aiku.numericalcontroloa.Model.Entity.MasterControl.MessageNotification;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.Order;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.OrderBilling;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.OrderCommission;
import aiku.numericalcontroloa.Model.Entity.OrderManagement.OrderGoods;
import aiku.numericalcontroloa.Model.Vo.OrderManagement.OrderBillingVo;
import aiku.numericalcontroloa.Model.Vo.OrderManagement.OrderGoodsVo;
import aiku.numericalcontroloa.Model.Vo.OrderManagement.OrderVo;
import aiku.numericalcontroloa.Model.Vo.OrderManagement.RoyaltyVo;
import aiku.numericalcontroloa.Service.OrderManagement.OrderService;
import aiku.numericalcontroloa.common.utils.DateUtils;
import aiku.numericalcontroloa.enums.RoleEnum;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 *
 * @Author 黄广庭
 * @Date 2024/3/19 12:02
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ClientsMapper clientsMapper;
    @Autowired
    private DevicesMapper devicesMapper;
    @Autowired
    private OrderBillingMapper orderBillingMapper;
    @Autowired
    private AfterSalesMapper afterSalesMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ExamineMapper examineMapper;
    @Autowired
    private DevicesOutboundMapper devicesOutboundMapper;
    @Autowired
    private OrderCommissionMapper orderCommissionMapper;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private IncomeExpenditureDetailMapper detailMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private RemarksMapper remarksMapper;
    @Autowired
    private CurrentMapper currentMapper;
    @Autowired
    private MessageNotificationMapper msgNotificationMapper;

    @Override
    @Transactional
    public Result addOrder(OrderDto orderDto) {
        if (orderDto == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        if (orderDto.getGoodsList().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        Order order = new Order();
        BeanUtils.copyProperties(orderDto, order);

        // 设置业务员
        if (orderDto.getUserId() == null || orderDto.getUserId().isEmpty()) {
            order.setUserId(StpUtil.getLoginIdAsString());
        } else {
            order.setUserId(orderDto.getUserId());
        }
        // 设置售后员
        if (orderDto.getAfterSaleId() != null && !orderDto.getAfterSaleId().isEmpty()) {
            order.setAfterSaleId(orderDto.getAfterSaleId());
        }
        // 生成订单流水号，时间戳
        order.setSn(String.valueOf(System.currentTimeMillis()));
        // 设置下单审核状态
        order.setOrderApprovalFlowId("0");
        // 订单状态为未收款
        order.setStatus(0);
        orderMapper.insert(order);

        // 订单零件记录
        for (OrderGoods orderGoods : orderDto.getGoodsList()) {
            orderGoods.setId(UUID.randomUUID().toString());
            orderGoods.setOrderId(order.getId());
            orderGoods.setCreateTime(new Date());
            orderGoods.setUpdateTime(new Date());
        }
        orderGoodsMapper.insertBatch(orderDto.getGoodsList());

        // 备注
        if (orderDto.getRemark() != null) {
            Remarks remarks = new Remarks();
            remarks.setQueryId(order.getId());
            remarks.setRemarkContent(orderDto.getRemark());
            remarksMapper.insert(remarks);
        }

        // 获取管理员角色
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        userLQW.eq(User::getState, BaseEnum.USER_INCUMBENCY.getCodeInt())
                .eq(User::getRoleId, RoleEnum.ROLE_1.getCodeToString());
        List<User> userList = userMapper.selectList(userLQW);
        if (!userList.isEmpty()) {
            // 获取客户
            Clients clients = clientsMapper.selectById(order.getClientsId());
            // 获取业务员
            User user = userMapper.selectById(order.getUserId());
            List<MessageNotification> msgList = new ArrayList<>();
            for (User admin : userList) {
                // 创建消息通知
                MessageNotification msg = new MessageNotification();
                msg.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                // 标题
                msg.setTitle("有新的订单下单申请待审批");
                // 内容
                String content = user.getNickName() + "申请为客户（" + clients.getName() + "）下单";
                msg.setContent(content);
                // 发布人为业务员
                msg.setPublisherId(user.getId());
                // 接收人为管理员
                msg.setReceiverId(admin.getId());
                // 关联id
                msg.setRelevanceId(order.getId());
                // 类型为订单管理
                msg.setMsgType(5);
                // 子菜单为1订单列表
                msg.setSubmenu(1);
                // 状态为待处理
                msg.setStatus(0);
                msg.setCreateTime(new Date());
                msgList.add(msg);
            }
            msgNotificationMapper.insertBatch(msgList);
        }
        return Result.success("添加成功");
    }

    @Override
    public Result deleteOrder(OrderDto orderDto) {
        if (orderDto == null || orderDto.getId() == null || orderDto.getId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        orderMapper.deleteById(orderDto.getId());
        return Result.success("删除成功");
    }

    @Override
    @Transactional
    public Result updateOrder(OrderDto orderDto) {
        if (orderDto == null || orderDto.getId() == null || orderDto.getId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查询是否有该订单
        Order order = orderMapper.selectById(orderDto.getId());
        if (order == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 客户
        if (orderDto.getClientsId() != null && !orderDto.getClientsId().isEmpty()) {
            order.setClientsId(orderDto.getClientsId());
        }
        // 交货日期
        if (orderDto.getDeliveryTime() != null) {
            order.setDeliveryTime(orderDto.getDeliveryTime());
        }
        // 总金额
        if (orderDto.getTransactionAmount() != null) {
            order.setTransactionAmount(orderDto.getTransactionAmount());
        }
        // 定金
        if (orderDto.getDeposit() != null) {
            order.setDeposit(orderDto.getDeposit());
        }
        // 首付款
        if (orderDto.getDownPayment() != null) {
            order.setDownPayment(orderDto.getDownPayment());
        }
        // 付款方式
        if (orderDto.getPaymentMethod() != null) {
            order.setPaymentMethod(orderDto.getPaymentMethod());
        }
        // 付款类型
        if (orderDto.getPaymentType() != null) {
            order.setPaymentType(orderDto.getPaymentType());
        }
        // 签订地点
        if (orderDto.getPlace() != null && !orderDto.getPlace().isEmpty()) {
            order.setPlace(orderDto.getPlace());
        }
        // 订单类型
        if (orderDto.getOrderType() != null) {
            order.setOrderType(orderDto.getOrderType());
        }
        // 付款方式
        if (orderDto.getPaymentMethod() != null) {
            order.setPaymentMethod(orderDto.getPaymentMethod());
        }
        // 还款截止时间
        if (orderDto.getDeadline() != null) {
            order.setDeadline(orderDto.getDeadline());
        }
        // 验收单url
        if (orderDto.getReceipt() != null && orderDto.getReceipt().isEmpty()) {
            order.setReceipt(orderDto.getReceipt());
        }
        // 物流信息url
        if (orderDto.getLogisticsInformation() != null && !orderDto.getLogisticsInformation().isEmpty()) {
            order.setLogisticsInformation(orderDto.getLogisticsInformation());
        }
        // 签订合同url
        if (orderDto.getContract() != null && !orderDto.getContract().isEmpty()) {
            order.setContract(orderDto.getContract());
        }
        // 将审核状态设为待审核
        order.setOrderApprovalFlowId("0");
        // 更新数据
        orderMapper.updateById(order);
        // 删除产品列表重新添加
        orderGoodsMapper.deleteBatchByOrderId(order.getId());
        for (OrderGoods orderGoods : orderDto.getGoodsList()) {
            orderGoods.setId(UUID.randomUUID().toString());
            orderGoods.setOrderId(order.getId());
            orderGoods.setCreateTime(new Date());
            orderGoods.setUpdateTime(new Date());
        }
        orderGoodsMapper.insertBatch(orderDto.getGoodsList());
        // 备注
        if (orderDto.getRemark() != null && !orderDto.getRemark().isEmpty()) {
            // 查是否有该备注
            LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
            remarksLQW.eq(Remarks::getQueryId, order.getId());
            Remarks remarks = remarksMapper.selectOne(remarksLQW);
            if (remarks == null) {
                // 没有就创建
                remarks = new Remarks();
                remarks.setQueryId(order.getId());
                remarks.setRemarkContent(orderDto.getRemark());
                remarksMapper.insert(remarks);
            } else {
                // 更新
                remarks.setRemarkContent(orderDto.getRemark());
                remarksMapper.updateById(remarks);
            }
        }
        return Result.success("修改成功");
    }

    @Override
    public Result updateOrderStatus(OrderDto orderDto) {
        if (orderDto == null || orderDto.getId() == null || orderDto.getStatus() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        LambdaUpdateWrapper<Order> orderLUW = new LambdaUpdateWrapper<>();
        orderLUW.eq(Order::getId, orderDto.getId())
                .set(Order::getStatus, orderDto.getStatus());
        orderMapper.update(null, orderLUW);
        return Result.success("修改成功");
    }

    @SuppressWarnings("unlikely-arg-type")
    @Override
    @Transactional
    public Result getOrderList(OrderDto orderDto) {
        if (orderDto == null || (orderDto.getCurrentPage() == null && orderDto.getPageSize() == null)) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        Page<Order> orderPage = new Page<>(orderDto.getCurrentPage(), orderDto.getPageSize());
        LambdaQueryWrapper<Order> orderLQW = new LambdaQueryWrapper<>();

        if (orderDto.getStatus() != null && orderDto.getStatus() == 0) {
            orderLQW.orderByDesc(Order::getTransactionAmount, Order::getCreateTime);
        } else {
            orderLQW.orderByDesc(Order::getCreateTime);
        }

        // 只有管理员能看全部
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        boolean role = user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString()) ||
                user.getRoleId().equals(RoleEnum.ROLE_5.getCodeToString());

        // 按客户模糊查询
        if (user.getRoleId().equals(RoleEnum.ROLE_3.getCodeToString())) {
            if (orderDto.getName() != null && !orderDto.getName().isEmpty()) {
                // 只能查自己的客户
                LambdaQueryWrapper<Clients> clientsLQW = new LambdaQueryWrapper<>();
                clientsLQW.like(Clients::getName, orderDto.getName()).or().like(Clients::getCompany,
                        orderDto.getName());
                List<String> clientsId = clientsMapper.selectList(clientsLQW)
                        .stream().map(Clients::getId).collect(Collectors.toList());
                if (clientsId.size() == 0) {
                    clientsId.add("");
                }
                orderLQW.in(Order::getClientsId, clientsId);
            }
            // 只能查自己的订单
            orderLQW.eq(Order::getUserId, user.getId());
        } else if (user.getRoleId().equals(RoleEnum.ROLE_6.getCodeToString())) {
            // 财务员查询业务员列表，再根据业务员查询客户id，再根据客户id查询订单
            LambdaQueryWrapper<Examine> examineLQW = new LambdaQueryWrapper<>();
            examineLQW.eq(Examine::getFinanceId, user.getId());
            List<String> userIdList = examineMapper.selectList(examineLQW).stream().map(Examine::getUserId)
                    .collect(Collectors.toList());
            if (userIdList.size() > 0) {
                if (orderDto.getName() != null && !orderDto.getName().isEmpty()) {
                    // 根据业务员模糊查询客户
                    Set<String> clientList = new HashSet<>();
                    for (String userId : userIdList) {
                        // 模糊搜索客户
                        LambdaQueryWrapper<Clients> clientsLQW = new LambdaQueryWrapper<>();
                        clientsLQW.eq(Clients::getSalesmanId, userId).like(Clients::getName, orderDto.getName()).or()
                                .like(Clients::getCompany, orderDto.getName());
                        List<String> clientsId = clientsMapper.selectList(clientsLQW)
                                .stream().map(Clients::getId).collect(Collectors.toList());
                        clientList.addAll(clientsId);
                    }
                    if (clientList.size() == 0) {
                        clientList.add("");
                    }
                    orderLQW.in(Order::getClientsId, clientList);
                }
                orderLQW.in(Order::getUserId, userIdList);
            } else {
                userIdList.add("");
                orderLQW.in(Order::getUserId, userIdList);
            }
        } else if (role) {
            // 管理员和厂长根据客户查询
            if (orderDto.getName() != null) {
                LambdaQueryWrapper<Clients> clientsLQW = new LambdaQueryWrapper<>();
                clientsLQW.like(Clients::getName, orderDto.getName()).or().like(Clients::getCompany,
                        orderDto.getName());
                List<String> clientsIdList = clientsMapper.selectList(clientsLQW)
                        .stream().map(Clients::getId).collect(Collectors.toList());
                if (clientsIdList.size() == 0) {
                    clientsIdList.add("");
                }
                orderLQW.in(Order::getClientsId, clientsIdList);
            }
        } else {
            if (orderDto.getName() != null && !orderDto.getName().isEmpty()) {
                // 只能查自己的客户
                LambdaQueryWrapper<Clients> clientsLQW = new LambdaQueryWrapper<>();
                clientsLQW.like(Clients::getName, orderDto.getName()).or().like(Clients::getCompany,
                        orderDto.getName());
                List<String> clientsId = clientsMapper.selectList(clientsLQW)
                        .stream().map(Clients::getId).collect(Collectors.toList());
                if (clientsId.size() == 0) {
                    clientsId.add("");
                }
                orderLQW.in(Order::getClientsId, clientsId);
            }
            // 只能查自己的订单
            orderLQW.eq(Order::getUserId, user.getId());
        }
        // 按订单状态查询
        if (orderDto.getStatus() != null) {
            orderLQW.eq(Order::getStatus, orderDto.getStatus());// transaction_amount
        }

        if (orderDto.getOrderApprovalFlowIdType() != null) {
            orderLQW.eq(Order::getOrderApprovalFlowId, orderDto.getOrderApprovalFlowIdType());
        }
        if (orderDto.getPaymentApprovalFlowIdType() != null) {
            orderLQW.eq(Order::getPaymentApprovalFlowId, orderDto.getPaymentApprovalFlowIdType());
        }

        // 按订单流水号查询
        if (orderDto.getSn() != null && !orderDto.getSn().isEmpty()) {
            orderLQW.like(Order::getSn, orderDto.getSn());
        }
        // 管理员按业务员查询
        if (role && orderDto.getUserId() != null && !orderDto.getUserId().isEmpty()) {
            orderLQW.eq(Order::getUserId, orderDto.getUserId());
        }
        // List<Order> orderList = orderMapper.selectPage(orderPage,
        // orderLQW).getRecords();
        List<Order> orderList = orderMapper.selectList(orderLQW);
        List<OrderVo> orderVoList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        if (orderList.isEmpty()) {
            map.put("total", 0);
            map.put("orderVoList", orderVoList);
            return Result.success("查询成功", map);
        }

        // 处理数据
        Set<String> orderIdList = orderList.stream().map(Order::getId).collect(Collectors.toSet());
        Set<String> clientsIdList = orderList.stream().map(Order::getClientsId).collect(Collectors.toSet());
        // 查客户
        List<Clients> clientsList = clientsMapper.selectBatchByIdWithDelete(clientsIdList);
        // 处理成map，根据客户id获取客户对象
        Map<String, Clients> clientsMap = clientsList.stream()
                .collect(Collectors.toMap(Clients::getId, Function.identity()));

        // 查业务员和售后员
        // 业务员
        Set<String> userIdList = orderList.stream().map(Order::getUserId).collect(Collectors.toSet());
        // 售后员
        Set<String> afterSalesIdList = orderList.stream().map(Order::getAfterSaleId).collect(Collectors.toSet());
        userIdList.addAll(afterSalesIdList);
        List<User> userList = userMapper.selectBatchByIdWithDelete(userIdList);
        // 处理成map集合，根据userId获取user
        Map<String, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

        // 查询产品列表
        LambdaQueryWrapper<OrderGoods> orderGoodsLQW = new LambdaQueryWrapper<>();
        orderGoodsLQW.in(OrderGoods::getOrderId, orderIdList);
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(orderGoodsLQW);
        Set<String> goodsIdList = orderGoodsList.stream().map(OrderGoods::getGoodsId).collect(Collectors.toSet());
        // 查询产品信息
        List<Devices> devicesList = devicesMapper.selectBatchByIdWithDelete(goodsIdList);
        // 根据产品id获取产品对象
        Map<String, Devices> devicesMap = devicesList.stream()
                .collect(Collectors.toMap(Devices::getId, Function.identity()));
        Map<String, List<OrderGoodsVo>> orderGoodsMap = new HashMap<>();
        for (OrderGoods orderGoods : orderGoodsList) {
            OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
            BeanUtils.copyProperties(orderGoods, orderGoodsVo);
            Devices devices = devicesMap.get(orderGoods.getGoodsId());
            orderGoodsVo.setPartName(devices.getPartName());
            orderGoodsVo.setModel(devices.getModel());
            orderGoodsVo.setIsProduct(devices.getIsProduct());
            orderGoodsVo.setPrice(devices.getPrice());
            orderGoodsVo.setImage(devices.getImage());
            orderGoodsVo.setCount(devices.getCount());
            orderGoodsVo.setDevicesDescribe(devices.getDevicesDescribe());
            orderGoodsVo.setRemark(devices.getRemark());
            if (orderGoodsMap.containsKey(orderGoods.getOrderId())) {
                orderGoodsMap.get(orderGoods.getOrderId()).add(orderGoodsVo);
            } else {
                List<OrderGoodsVo> orderGoodsVoList = new ArrayList<>();
                orderGoodsVoList.add(orderGoodsVo);
                orderGoodsMap.put(orderGoods.getOrderId(), orderGoodsVoList);
            }
        }

        // 查询订单账单
        LambdaQueryWrapper<OrderBilling> orderBillingLQW = new LambdaQueryWrapper<>();
        orderBillingLQW.in(OrderBilling::getOrderId, orderIdList);
        List<OrderBilling> orderBillingList = orderBillingMapper.selectList(orderBillingLQW);
        Map<String, List<OrderBilling>> orderBillingListMap = new HashMap<>();
        if (orderBillingList.size() > 0) {
            for (OrderBilling orderBilling : orderBillingList) {
                if (orderBillingListMap.containsKey(orderBilling.getOrderId())) {
                    orderBillingListMap.get(orderBilling.getOrderId()).add(orderBilling);
                } else {
                    List<OrderBilling> orderBillings = new ArrayList<>();
                    orderBillings.add(orderBilling);
                    orderBillingListMap.put(orderBilling.getOrderId(), orderBillings);
                }
            }
        }

        // 查备注
        LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
        remarksLQW.in(Remarks::getQueryId, orderIdList);
        List<Remarks> remarksList = remarksMapper.selectList(remarksLQW);
        Map<String, Remarks> remarksMap = remarksList.stream()
                .collect(Collectors.toMap(Remarks::getQueryId, r -> remarksList.stream()
                        .filter(remarks -> remarks.getId().equals(r.getId()))
                        .findFirst()
                        .orElse(null)));

        // 需要更新的订单集合
        List<Order> newOrderList = new ArrayList<>();
        // 需要更新的订单账单集合
        List<OrderBilling> newOrderBillingList = new ArrayList<>();

        for (Order order : orderList) {
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(order, orderVo);
            // 客户信息
            Clients clients = clientsMap.get(order.getClientsId());
            orderVo.setName(clients.getName());
            orderVo.setCompany(clients.getCompany());
            orderVo.setPhone(clients.getPhone());
            String address = clients.getProvince() + clients.getCity() + clients.getDistrict() + clients.getAddress();
            orderVo.setAddress(address);
            // 业务员信息
            User user1 = userMap.get(order.getUserId());
            orderVo.setNickName(user1.getNickName());
            // 售后员信息
            if (order.getAfterSaleId() != null && !order.getAfterSaleId().isEmpty()) {
                User afterSale = userMap.get(order.getAfterSaleId());
                orderVo.setAfterSaleName(afterSale.getNickName());
            }
            // 备注
            if (remarksMap.containsKey(order.getId())) {
                Remarks remarks = remarksMap.get(order.getId());
                orderVo.setRemark(remarks.getRemarkContent());
            }
            // 产品列表
            orderVo.setGoodsList(orderGoodsMap.get(order.getId()));
            // 设置下单审批状态
            orderVo.setOrderFlowId(order.getOrderApprovalFlowId());
            // 设置收款审批状态
            orderVo.setPaymentFlowId(order.getPaymentApprovalFlowId());
            // 每月还款日
            LocalDate orderCreateDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            int repaymentDate = Integer.parseInt(orderCreateDate.toString().split("-")[2]);
            orderVo.setRepaymentDate(repaymentDate);
            // 订单为合同
            if (order.getOrderType() == 2) {
                // 尾款，总金额-定金-首付款
                BigDecimal balancePayment = (order.getTransactionAmount().subtract(order.getDeposit()))
                        .subtract(order.getDownPayment());
                orderVo.setBalancePayment(balancePayment);
                // 每期应还，末期应还
                if (order.getPaymentMethod() > 0) {
                    // 分期付款，每期应还 = 尾款/期数；
                    // 计算每期金额
                    long phaseAmount = (orderVo.getBalancePayment()
                            .divide(BigDecimal.valueOf(orderVo.getPaymentMethod()), 0, RoundingMode.DOWN)).longValue();
                    orderVo.setPhaseAmount(BigDecimal.valueOf(phaseAmount));
                    // 计算缺失金额
                    BigDecimal deficiency = orderVo.getBalancePayment()
                            .subtract(BigDecimal.valueOf(phaseAmount * orderVo.getPaymentMethod()));
                    // 末期金额，每期加上缺失金额
                    BigDecimal lastAmount = BigDecimal.valueOf(phaseAmount).add(deficiency);
                    orderVo.setLastAmount(lastAmount);
                }

            }
            // 剩余待还金额
            BigDecimal arrears = order.getTransactionAmount();
            if (order.getOrderApprovalFlowId().equals("1")) {
                // 通过下单审核，查订单账单
                List<OrderBilling> billingList = orderBillingListMap.get(order.getId());
                // 计算剩余期数，未收款和逾期，剩余待还金额
                int count = 0;
                // 订单状态
                int status = 0;
                arrears = new BigDecimal(0);
                for (OrderBilling orderBilling : billingList) {
                    // 判断是否逾期
                    int comparisonResult = LocalDate.now().compareTo(orderBilling.getRepaymentDate());
                    if (comparisonResult > 0 && order.getStatus() != 1 && orderBilling.getBillStatus() != 1) {
                        // 现在时间大于账单还款时间，且订单状态不为已收款
                        // 逾期将账单状态设置为逾期
                        orderBilling.setBillStatus(2);
                        // 放入待更新的集合中
                        newOrderBillingList.add(orderBilling);
                    }
                    if (orderBilling.getBillStatus() != 1 && orderBilling.getCurrentPeriod() > 0
                            && order.getPaymentMethod() > 0) {
                        // 订单账单为待付款逾期，且订单账单不为定金期和首付款期，且订单为分期类型
                        // 剩余期数，排除了定金期和首付款
                        count++;
                    }
                    if (status != 2 && orderBilling.getBillStatus() == 2) {
                        // 订单账单有逾期，将订单状态设置为逾期
                        status = 2;
                    }
                    if (orderBilling.getBillStatus() != 1) {
                        // 订单账单为未付款和欠款
                        arrears = arrears.add(orderBilling.getAmount());
                        if (arrears.compareTo(order.getTransactionAmount()) == 1) {
                            arrears = order.getTransactionAmount();
                        }
                    }
                }
                if (status != order.getStatus() && order.getStatus() != 1) {
                    // 将订单放入待更新集合中
                    orderVo.setStatus(status);
                    order.setStatus(status);
                    newOrderList.add(order);
                }
                if (order.getPaymentMethod() > 0) {
                    // 付款方式为分期，设置剩余期数
                    orderVo.setResiduePeriods(count);
                }
            } else if (!orderVo.getOrderFlowId().equals("1") && orderVo.getPaymentMethod() > 0) {
                // 订单审核未通过，且为分期
                // 设置剩余期数
                orderVo.setResiduePeriods(orderVo.getPaymentMethod());
            }
            // 设置剩余还款金额
            orderVo.setArrears(arrears);
            orderVo.setCreateTime(DateUtils.YMDHMSFormat(order.getCreateTime()));
            // 身份证照片
            if (order.getCopyOfIdCard() != null) {
                orderVo.setCopyOfIdCardList(order.getCopyOfIdCard().split(";"));
            }
            // 验收单
            if (order.getReceipt() != null) {
                orderVo.setReceiptList(order.getReceipt().split(";"));
            }
            // 物流单
            if (order.getLogisticsInformation() != null) {
                orderVo.setLogisticsInformationList(order.getLogisticsInformation().split(";"));
            }
            // 合同单
            if (order.getContract() != null) {
                orderVo.setContractList(order.getContract().split(";"));
            }
            orderVoList.add(orderVo);
        }
        // 更新订单账单
        if (!newOrderBillingList.isEmpty()) {
            orderBillingMapper.updateBatchForStatus(newOrderBillingList);
        }
        // 更新订单
        if (!newOrderList.isEmpty()) {
            orderMapper.updateBatchForStatus(newOrderList);
        }

        if (orderDto.getStatus() != null && orderDto.getStatus() == 2) {
            orderVoList = orderVoList.stream().sorted(Comparator.comparing(OrderVo::getArrears).reversed())
                    .collect(Collectors.toList());
        }
        if (orderDto.getCollectedType() != null && orderDto.getCollectedType().equals("0")) {
            orderVoList = orderVoList.stream().filter(item -> item.getTransactionAmount().equals(item.getArrears()))
                    .collect(Collectors.toList());
        } else if (orderDto.getCollectedType() != null && orderDto.getCollectedType().equals("1")) {
            orderVoList = orderVoList.stream().filter(item -> item.getArrears().equals(BigDecimal.ZERO))
                    .collect(Collectors.toList());
        } else if (orderDto.getCollectedType() != null && orderDto.getCollectedType().equals("2")) {
            orderVoList = orderVoList.stream().filter(
                    item -> !item.getTransactionAmount().equals(item.getArrears())
                            && !item.getArrears().equals(BigDecimal.ZERO))
                    .collect(Collectors.toList());
        }

        int listLength = orderVoList.size();
        int selectPageStart = (int) ((orderPage.getCurrent() - 1) * orderPage.getSize());
        int selectPageEnd = (int) (orderPage.getCurrent() * orderPage.getSize());
        if (selectPageEnd > listLength) {
            selectPageEnd = listLength;
        }
        List<OrderVo> newList = orderVoList.subList(selectPageStart, selectPageEnd);

        // map.put("total", orderPage.getTotal());
        map.put("total", listLength);
        map.put("orderVoList", newList);
        return Result.success("查询成功", map);
    }

    @Override
    @Transactional
    public Result getOrder(OrderDto orderDto) {
        if (orderDto == null || orderDto.getId() == null || orderDto.getId().isEmpty()) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 查是否有该订单
        Order order = orderMapper.selectById(orderDto.getId());
        if (order == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该订单不存在");
        }
        OrderVo orderVo = new OrderVo();
        BeanUtils.copyProperties(order, orderVo);
        // 设置客户
        Clients clients = clientsMapper.selectByIdWithDelete(order.getClientsId());
        orderVo.setName(clients.getName());
        orderVo.setCompany(clients.getCompany());
        orderVo.setPhone(clients.getPhone());
        String address = clients.getProvince() + clients.getCity() + clients.getDistrict() + clients.getAddress();
        orderVo.setAddress(address);
        // 设置业务员
        User user = userMapper.selectById(order.getUserId());
        orderVo.setNickName(user.getNickName());
        // 设置售后员
        if (order.getAfterSaleId() != null) {
            User afterSale = userMapper.selectById(order.getAfterSaleId());
            orderVo.setAfterSaleName(afterSale.getNickName());
        }
        // 备注
        LambdaQueryWrapper<Remarks> remarksLQW = new LambdaQueryWrapper<>();
        remarksLQW.eq(Remarks::getQueryId, order.getId());
        Remarks remarks = remarksMapper.selectOne(remarksLQW);
        if (remarks != null) {
            orderVo.setRemark(remarks.getRemarkContent());
        }

        // 设置产品列表
        LambdaQueryWrapper<OrderGoods> orderGoodsLQW = new LambdaQueryWrapper<>();
        orderGoodsLQW.eq(OrderGoods::getOrderId, order.getId());
        List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(orderGoodsLQW);
        // 根据产品id查询产品
        List<String> goodsIdList = orderGoodsList.stream().map(OrderGoods::getGoodsId).collect(Collectors.toList());
        List<Devices> devicesList = devicesMapper.selectBatchByIdWithDelete(goodsIdList);
        Map<String, Devices> devicesMap = devicesList.stream()
                .collect(Collectors.toMap(Devices::getId, d -> devicesList.stream()
                        .filter(devices -> devices.getId().equals(d.getId()))
                        .findFirst()
                        .orElse(null)));
        List<OrderGoodsVo> orderGoodsVoList = new ArrayList<>();
        for (OrderGoods orderGoods : orderGoodsList) {
            OrderGoodsVo orderGoodsVo = new OrderGoodsVo();
            Devices devices = devicesMap.get(orderGoods.getGoodsId());
            BeanUtils.copyProperties(orderGoods, orderGoodsVo);
            orderGoodsVo.setPartName(devices.getPartName());
            orderGoodsVo.setModel(devices.getModel());
            orderGoodsVo.setIsProduct(devices.getIsProduct());
            orderGoodsVo.setPrice(devices.getPrice());
            orderGoodsVo.setImage(devices.getImage());
            orderGoodsVo.setCount(devices.getCount());
            orderGoodsVo.setDevicesDescribe(devices.getDevicesDescribe());
            orderGoodsVo.setRemark(devices.getRemark());
            orderGoodsVoList.add(orderGoodsVo);
        }
        orderVo.setGoodsList(orderGoodsVoList);
        // 设置下单审批状态
        orderVo.setOrderFlowId(order.getOrderApprovalFlowId());
        // 设置收款审批状态
        orderVo.setPaymentFlowId(order.getPaymentApprovalFlowId());
        // 每月还款日
        LocalDate orderCreateDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        int repaymentDate = Integer.parseInt(orderCreateDate.toString().split("-")[2]);
        orderVo.setRepaymentDate(repaymentDate);

        // 订单为合同
        if (order.getOrderType() == 2) {
            // 尾款，总金额-定金-首付款
            BigDecimal balancePayment = (order.getTransactionAmount().subtract(order.getDeposit()))
                    .subtract(order.getDownPayment());
            orderVo.setBalancePayment(balancePayment);
            // 每期应还，末期应还
            if (order.getPaymentMethod() > 0) {
                // 分期付款，每期应还 = 尾款/期数；
                // 计算每期金额
                long phaseAmount = (orderVo.getBalancePayment().divide(BigDecimal.valueOf(orderVo.getPaymentMethod()),
                        0, RoundingMode.DOWN)).longValue();
                orderVo.setPhaseAmount(BigDecimal.valueOf(phaseAmount));
                // 计算缺失金额
                BigDecimal deficiency = orderVo.getBalancePayment()
                        .subtract(BigDecimal.valueOf(phaseAmount * orderVo.getPaymentMethod()));
                // 末期金额，每期加上缺失金额
                BigDecimal lastAmount = BigDecimal.valueOf(phaseAmount).add(deficiency);
                orderVo.setLastAmount(lastAmount);
            }
        }

        // 剩余还款金额
        BigDecimal arrears = order.getTransactionAmount();
        // 订单通过审核，查询订单账单信息
        if (orderVo.getOrderFlowId().equals("1")) {
            // 通过订单审核
            // 查询订单账单
            LambdaQueryWrapper<OrderBilling> orderBillingLQW = new LambdaQueryWrapper<>();
            orderBillingLQW.eq(OrderBilling::getOrderId, orderVo.getId());
            List<OrderBilling> orderBillingList = orderBillingMapper.selectList(orderBillingLQW);
            // 计算剩余期数，未收款和逾期，剩余待还金额
            int count = 0;
            int status = 0;
            arrears = new BigDecimal(0);
            for (OrderBilling orderBilling : orderBillingList) {
                // 判断是否逾期
                int comparisonResult = LocalDate.now().compareTo(orderBilling.getRepaymentDate());
                if (comparisonResult > 0 && order.getStatus() != 1 && orderBilling.getBillStatus() != 1) {
                    // 现在时间大于账单还款时间，且订单状态不为已收款，且订单账单不为已收款
                    // 逾期将账单状态设置为逾期
                    orderBilling.setBillStatus(2);
                    LambdaUpdateWrapper<OrderBilling> orderBillingLUW = new LambdaUpdateWrapper<>();
                    orderBillingLUW.eq(OrderBilling::getId, orderBilling.getId())
                            .set(OrderBilling::getBillStatus, orderBilling.getBillStatus());
                    orderBillingMapper.update(null, orderBillingLUW);
                }
                if (orderBilling.getBillStatus() != 1 && orderBilling.getCurrentPeriod() > 0
                        && order.getPaymentMethod() > 0) {
                    // 订单账单为待付款逾期，且订单账单不为定金期和首付款期，且订单为分期类型
                    // 剩余期数，排除了定金期
                    count++;
                }
                if (status != 2 && orderBilling.getBillStatus() == 2) {
                    // 订单账单有逾期，将订单状态设置为逾期
                    status = 2;
                }
                if (orderBilling.getBillStatus() != 1) {
                    // 订单账单为未付款和欠款
                    arrears = arrears.add(orderBilling.getAmount());
                }
            }
            if (status != order.getStatus() && order.getStatus() != 1) {
                // 更新订单状态
                orderVo.setStatus(status);
                LambdaUpdateWrapper<Order> orderLUW = new LambdaUpdateWrapper<>();
                orderLUW.eq(Order::getId, order.getId()).set(Order::getStatus, status);
                orderMapper.update(null, orderLUW);
            }
            if (order.getPaymentMethod() > 0) {
                // 付款方式为分期，设置剩余期数
                orderVo.setResiduePeriods(count);
            }
        } else if (!orderVo.getOrderFlowId().equals("1") && orderVo.getPaymentMethod() > 0) {
            // 订单审核未通过，且为分期
            // 设置剩余期数
            orderVo.setResiduePeriods(orderVo.getPaymentMethod());
        }
        // 设置剩余还款金额
        orderVo.setArrears(arrears);
        orderVo.setCreateTime(DateUtils.YMDHMSFormat(order.getCreateTime()));
        // 身份证照片
        if (order.getCopyOfIdCard() != null) {
            orderVo.setCopyOfIdCardList(order.getCopyOfIdCard().split(";"));
        }
        // 验收单
        if (order.getReceipt() != null) {
            orderVo.setReceiptList(order.getReceipt().split(";"));
        }
        // 物流单
        if (order.getLogisticsInformation() != null) {
            orderVo.setLogisticsInformationList(order.getLogisticsInformation().split(";"));
        }
        // 合同单
        if (order.getContract() != null) {
            orderVo.setContractList(order.getContract().split(";"));
        }
        return Result.success("查询成功", orderVo);
    }

    @Override
    public Result orderDelivery(OrderDto orderDto) {
        if (orderDto == null || orderDto.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        LambdaUpdateWrapper<Order> orderLUW = new LambdaUpdateWrapper<>();
        orderLUW.eq(Order::getId, orderDto.getId());
        if (orderDto.getCopyOfIdCard() != null && !orderDto.getCopyOfIdCard().isEmpty()) {
            orderLUW.set(Order::getCopyOfIdCard, orderDto.getCopyOfIdCard());
        } else if (orderDto.getCopyOfIdCard() != null && orderDto.getCopyOfIdCard().isEmpty()) {
            orderLUW.set(Order::getCopyOfIdCard, null);
        }
        if (orderDto.getReceipt() != null && !orderDto.getReceipt().isEmpty()) {
            orderLUW.set(Order::getReceipt, orderDto.getReceipt());
        } else if (orderDto.getReceipt() != null && orderDto.getReceipt().isEmpty()) {
            orderLUW.set(Order::getReceipt, null);
        }
        if (orderDto.getLogisticsInformation() != null && !orderDto.getLogisticsInformation().isEmpty()) {
            orderLUW.set(Order::getLogisticsInformation, orderDto.getLogisticsInformation());
        } else if (orderDto.getLogisticsInformation() != null && orderDto.getLogisticsInformation().isEmpty()) {
            orderLUW.set(Order::getLogisticsInformation, null);
        }
        if (orderDto.getContract() != null && !orderDto.getContract().isEmpty()) {
            orderLUW.set(Order::getContract, orderDto.getContract());
        } else if (orderDto.getContract() != null && orderDto.getContract().isEmpty()) {
            orderLUW.set(Order::getContract, null);
        }
        orderMapper.update(null, orderLUW);
        return Result.success("上传成功");
    }

    @Override
    @Transactional
    public Result orderExamine(OrderDto orderDto) {
        if (orderDto == null || orderDto.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 管理员有权
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        if (!user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString())) {
            return new Result(HttpStatus.FORBIDDEN, "无权访问");
        }
        Order order = orderMapper.selectById(orderDto.getId());
        if (order == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该订单不存在");
        }
        order.setOrderApprovalFlowId(orderDto.getOrderApprovalFlowId());
        LambdaUpdateWrapper<Order> orderLUW = new LambdaUpdateWrapper<>();
        orderLUW.eq(Order::getId, order.getId())
                .set(Order::getOrderApprovalFlowId, orderDto.getOrderApprovalFlowId());
        orderMapper.update(null, orderLUW);

        // 订单审核通过后，创建订单账单
        // 订单创建日期
        LocalDate orderCreateDate = order.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 判断订单是否通过，且是否分期
        if (order.getOrderApprovalFlowId().equals("1") && order.getPaymentMethod() > 0) {
            // 计算分期订单的每期金额和末期金额
            // 尾款，总金额-定金-首付款
            BigDecimal balancePayment = (order.getTransactionAmount().subtract(order.getDeposit()))
                    .subtract(order.getDownPayment());
            // 每期金额，尾款除以期数，不要小数，不四舍五入
            long longPhaseAmount = (balancePayment.divide(BigDecimal.valueOf(order.getPaymentMethod()), 0,
                    RoundingMode.DOWN)).longValue();
            BigDecimal phaseAmount = BigDecimal.valueOf(longPhaseAmount);
            // 缺失金额，尾款-每期*总期数
            BigDecimal deficiency = balancePayment
                    .subtract(phaseAmount.multiply(BigDecimal.valueOf(order.getPaymentMethod())));
            // 末期金额，每期加缺失
            BigDecimal lastAmount = phaseAmount.add(deficiency);

            // 通过且为分期，创建分期账单
            for (int i = -1; i <= order.getPaymentMethod(); i++) {
                OrderBilling orderBilling = new OrderBilling();
                orderBilling.setOrderId(order.getId());
                // 总期数
                orderBilling.setTotalPeriod(order.getPaymentMethod());
                // 本期，i=-1则为定金期，i=0则为首付款期
                orderBilling.setCurrentPeriod(i);

                // 定金期
                if (i == -1) {
                    // 定金期的金额
                    orderBilling.setAmount(order.getDeposit());
                    // 交付日期为定金最后收款日
                    orderBilling.setRepaymentDate(order.getDeliveryTime());
                } else if (i == 0) {
                    // 首付款期
                    orderBilling.setAmount(order.getDownPayment());
                    // 交付日期为首付款最后收款日
                    orderBilling.setRepaymentDate(order.getDeliveryTime());
                } else {
                    // 金额
                    // 判断是否为末期
                    if (i == order.getPaymentMethod()) {
                        // 为最后一期，金额为末期金额
                        orderBilling.setAmount(lastAmount);
                    } else {
                        orderBilling.setAmount(phaseAmount);
                    }
                    // 还款日
                    // 订单创建时间日期开始
                    orderBilling.setRepaymentDate(orderCreateDate.plusMonths(i));
                }
                // 账单状态为未收款
                orderBilling.setBillStatus(0);
                orderBillingMapper.insert(orderBilling);
            }
        } else if (order.getOrderApprovalFlowId().equals("1") && order.getOrderType() == 2
                && order.getPaymentMethod() == 0) {
            // 订单审核通过，且订单为签订合同，且付款方式为全款
            // 尾款，总金额-定金-首付款
            BigDecimal balancePayment = (order.getTransactionAmount().subtract(order.getDeposit()))
                    .subtract(order.getDownPayment());
            // 生成订单账单
            for (int i = -1; i < 2; i++) {
                OrderBilling orderBilling = new OrderBilling();
                orderBilling.setOrderId(order.getId());
                // 总期数
                orderBilling.setTotalPeriod(1);
                // 本期，i=-1则为定金期，i=0则为首付款期
                orderBilling.setCurrentPeriod(i);
                if (i == -1) {
                    // 定金期的金额
                    orderBilling.setAmount(order.getDeposit());
                    // 交付日期为定金最后收款日
                    orderBilling.setRepaymentDate(order.getDeliveryTime());
                } else if (i == 0) {
                    // 首付款期
                    orderBilling.setAmount(order.getDownPayment());
                    // 交付日期为首付款最后收款日
                    orderBilling.setRepaymentDate(order.getDeliveryTime());
                } else {
                    // 不为定金期，金额为尾款
                    orderBilling.setAmount(balancePayment);
                    // 还款日
                    // 订单创建时间日期开始后一个月，为尾款最后收款日
                    orderBilling.setRepaymentDate(orderCreateDate.plusMonths(i));
                }
                // 账单状态为未收款
                orderBilling.setBillStatus(0);
                orderBillingMapper.insert(orderBilling);
            }
        } else if (order.getOrderApprovalFlowId().equals("1") && order.getOrderType() == 1) {
            // 订单审核通过，且订单类型为开销开单
            // 开销开单只有全款
            OrderBilling orderBilling = new OrderBilling();
            orderBilling.setOrderId(order.getId());
            // 总期数为0
            orderBilling.setTotalPeriod(0);
            // 本期为0
            orderBilling.setCurrentPeriod(0);
            // 金额为总金额
            orderBilling.setAmount(order.getTransactionAmount());
            // 最后收款日为交付日期
            orderBilling.setRepaymentDate(order.getDeliveryTime());
            // 账单状态为未收款
            orderBilling.setBillStatus(0);
            orderBillingMapper.insert(orderBilling);
        }
        User salesman = userMapper.selectById(order.getUserId());
        if (order.getOrderApprovalFlowId().equals("1")) {
            // 订单通过，创建出库记录
            DevicesOutbound devicesOutbound = new DevicesOutbound();
            // 设置订单id
            devicesOutbound.setReturnId(order.getId());
            // 设置出库申请人
            devicesOutbound.setUserId(salesman.getId());
            devicesOutbound.setApplicant(salesman.getNickName());
            // 设置出库价格
            devicesOutbound.setPrice(order.getTransactionAmount());
            // 设置出库类型为卖出商品
            devicesOutbound.setType(0);
            // 设置出库状态为待申请
            devicesOutbound.setStatus(3);
            Remarks Rstr = remarksMapper
                    .selectOne(new LambdaQueryWrapper<Remarks>().eq(Remarks::getQueryId, order.getId()));
            if (Rstr != null) {
                devicesOutbound.setRemark(Rstr.getRemarkContent());
            }
            devicesOutboundMapper.insert(devicesOutbound);
        }
        String approval;
        if (order.getOrderApprovalFlowId().equals("1")) {
            approval = "已通过";
        } else {
            approval = "未通过";
        }
        // 创建消息通知
        MessageNotification msg = new MessageNotification();
        // 标题
        String title = "订单下单申请" + approval;
        msg.setTitle(title);
        // 内容
        Clients clients = clientsMapper.selectById(order.getClientsId());
        String content = "您为客户（" + clients.getName() + "）下单的申请" + approval;
        msg.setContent(content);
        // 发布人为审核人
        msg.setPublisherId(user.getId());
        // 接收人为业务员
        msg.setReceiverId(salesman.getId());
        // 关联id
        msg.setRelevanceId(order.getId());
        // 类型为订单管理
        msg.setMsgType(5);
        // 子菜单为3订单详情
        msg.setSubmenu(3);
        // 状态为待处理
        msg.setStatus(0);
        msgNotificationMapper.insert(msg);
        return Result.success("修改成功");
    }

    @Override
    public Result getOrderBillingList(OrderBillingDto orderBillingDto) {
        if (orderBillingDto == null || orderBillingDto.getOrderId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        LambdaQueryWrapper<OrderBilling> orderBillingLQW = new LambdaQueryWrapper<>();
        orderBillingLQW.eq(OrderBilling::getOrderId, orderBillingDto.getOrderId())
                .orderByAsc(OrderBilling::getCurrentPeriod);
        // 根据账单状态查询
        if (orderBillingDto.getBillStatus() != null && orderBillingDto.getBillStatus() == 3) {
            orderBillingLQW.ne(OrderBilling::getBillStatus, 1);
        } else if (orderBillingDto.getBillStatus() != null) {
            orderBillingLQW.eq(OrderBilling::getBillStatus, orderBillingDto.getBillStatus());
        }
        List<OrderBilling> orderBillingList = orderBillingMapper.selectList(orderBillingLQW);
        List<OrderBillingVo> orderBillingVoList = new ArrayList<>();
        if (orderBillingList.size() > 0) {
            for (OrderBilling orderBilling : orderBillingList) {
                OrderBillingVo orderBillingVo = new OrderBillingVo();
                BeanUtils.copyProperties(orderBilling, orderBillingVo);
                if (orderBilling.getDateReceived() != null) {
                    orderBillingVo.setDateReceived(DateUtils.YMDHMSFormat(orderBilling.getDateReceived()));
                }
                if (orderBilling.getAccount() != null) {
                    Account account = accountMapper.selectByIdWithDelete(orderBilling.getAccount());
                    orderBillingVo.setAccount(account.getAccount());
                    orderBillingVo.setAccountId(account.getId());
                }
                orderBillingVoList.add(orderBillingVo);
            }
        }
        return Result.success("查询成功", orderBillingVoList);
    }

    @Override
    @Transactional
    public Result application(OrderBilling orderBilling) {
        if (orderBilling == null || orderBilling.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        OrderBilling OBilling = orderBillingMapper.selectById(orderBilling.getId());
        if (OBilling == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该账单不存在");
        }
        Order order = orderMapper.selectById(OBilling.getOrderId());
        if (!order.getOrderApprovalFlowId().equals("1")) {
            return new Result(HttpStatus.BAD_REQUEST, "该订单不存在");
        }
        LambdaUpdateWrapper<Order> orderLUW = new LambdaUpdateWrapper<>();
        orderLUW.eq(Order::getId, order.getId()).set(Order::getPaymentApprovalFlowId, 0);
        orderMapper.update(null, orderLUW);
        // 更新数据
        LambdaUpdateWrapper<OrderBilling> orderBillingLUW = new LambdaUpdateWrapper<>();
        orderBillingLUW.eq(OrderBilling::getId, OBilling.getId())
                .set(OrderBilling::getFundsReceived, orderBilling.getFundsReceived())
                .set(OrderBilling::getDateReceived, new Date())
                .set(OrderBilling::getAccount, orderBilling.getAccount())
                .set(OrderBilling::getExamineStatus, 1);
        orderBillingMapper.update(null, orderBillingLUW);
        // 创建消息通知
        MessageNotification msg = new MessageNotification();
        // 标题
        msg.setTitle("有新的收款申请待审批");
        // 内容
        User user = userMapper.selectById(order.getUserId());
        String content = user.getNickName() + "申请收款" + orderBilling.getFundsReceived() + "元";
        msg.setContent(content);
        // 发布人为业务员
        msg.setPublisherId(user.getId());
        // 接收人为审核业务员的财务员
        // 查审核业务员的财务员
        LambdaQueryWrapper<Examine> examineLQW = new LambdaQueryWrapper<>();
        examineLQW.eq(Examine::getUserId, order.getUserId());
        Examine examine = examineMapper.selectOne(examineLQW);
        msg.setReceiverId(examine.getFinanceId());
        // 关联id
        msg.setRelevanceId(order.getId());
        // 类型为订单管理
        msg.setMsgType(5);
        // 子菜单为1订单列表
        msg.setSubmenu(1);
        // 状态为待处理
        msg.setStatus(0);
        msgNotificationMapper.insert(msg);
        return Result.success("修改成功");
    }

    @Override
    @Transactional
    public Result collectionAudit(OrderDto orderDto) {
        if (orderDto == null || orderDto.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        // 管理员和财务有权
        User user = userMapper.selectById(StpUtil.getLoginIdAsString());
        if (!user.getRoleId().equals(RoleEnum.ROLE_1.getCodeToString()) &&
                !user.getRoleId().equals(RoleEnum.ROLE_6.getCodeToString())) {
            return new Result(HttpStatus.FORBIDDEN, "无权访问");
        }
        Order order = orderMapper.selectById(orderDto.getId());
        if (order == null) {
            return new Result(HttpStatus.BAD_REQUEST, "该订单不存在");
        }
        if (orderDto.getPaymentApprovalFlowId().equals("0")) {
            order.setPaymentApprovalFlowId("0");
        } else if (orderDto.getPaymentApprovalFlowId().equals("1")) {
            order.setPaymentApprovalFlowId("1");
        } else if (orderDto.getPaymentApprovalFlowId().equals("2")) {
            order.setPaymentApprovalFlowId("2");
        }

        // 判断收款审核是否通过
        OrderBilling orderBilling = orderBillingMapper.selectById(orderDto.getOrderBillingId());
        if (orderDto.getPaymentApprovalFlowId().equals("1")) {
            // 通过
            if (orderBilling == null) {
                return new Result(HttpStatus.BAD_REQUEST, "该账单不存在");
            }
            // 设置收款账户
            // 查询账户
            Account account = accountMapper.selectById(orderBilling.getAccount());
            if (account == null) {
                return new Result(HttpStatus.BAD_REQUEST, "该账户不存在");
            }
            orderBilling.setAccount(account.getId());
            // 设置账单状态为已收款
            orderBilling.setBillStatus(1);
            // 设置业务员提成id
            // 查询业务员提成
            LambdaQueryWrapper<OrderCommission> orderCommissionLQW = new LambdaQueryWrapper<>();
            orderCommissionLQW.eq(OrderCommission::getUserId, order.getUserId());
            OrderCommission salesmanCommission = orderCommissionMapper.selectOne(orderCommissionLQW);
            orderBilling.setSalesmanCommissionId(salesmanCommission.getId());

            // 设置售后员提成id
            if (order.getAfterSaleId() != null && !order.getAfterSaleId().isEmpty()) {
                orderCommissionLQW = new LambdaQueryWrapper<>();
                orderCommissionLQW.eq(OrderCommission::getUserId, order.getAfterSaleId());
                OrderCommission afterSaleCommission = orderCommissionMapper.selectOne(orderCommissionLQW);
                orderBilling.setAfterSalesCommissionId(afterSaleCommission.getId());
            }

            // 判断是否为最后一期
            if (orderBilling.getTotalPeriod().equals(orderBilling.getCurrentPeriod())) {
                // 等于最后一期，设置收款审核通过
                order.setPaymentApprovalFlowId(orderDto.getPaymentApprovalFlowId());
                // 设置当前订单为通过
                order.setStatus(1);
                // 更新数据
                LambdaUpdateWrapper<OrderBilling> orderBillingLUW = new LambdaUpdateWrapper<>();
                orderBillingLUW.eq(OrderBilling::getId, orderBilling.getId())
                        .set(OrderBilling::getAccount, orderBilling.getAccount())
                        .set(OrderBilling::getBillStatus, orderBilling.getBillStatus())
                        .set(OrderBilling::getSalesmanCommissionId, orderBilling.getSalesmanCommissionId())
                        .set(OrderBilling::getAfterSalesCommissionId, orderBilling.getAfterSalesCommissionId());
                orderBillingMapper.update(null, orderBillingLUW);

                // 新增账户明细
                IncomeExpenditureDetail detail = new IncomeExpenditureDetail();
                // 设置账户id
                detail.setAccountId(account.getId());
                // 设置订单id
                detail.setExpenseId(orderBilling.getId());
                // 设置明细类型为收款
                detail.setDetailType(BaseEnum.ACCOUNT_DETAIL_TYPE_COLLECTION.getCodeInt());
                // 计算余额
                account.setBalance(account.getBalance().add(orderBilling.getFundsReceived()));
                // 更新账户余额
                LambdaUpdateWrapper<Account> accountLUW = new LambdaUpdateWrapper<>();
                accountLUW.eq(Account::getId, account.getId())
                        .set(Account::getBalance, account.getBalance());
                accountMapper.update(null, accountLUW);
                // 设置余额
                detail.setBalance(account.getBalance());
                // 设置交易时间
                detail.setTradingHours(orderBilling.getDateReceived());
                // 设置交易说明
                if (orderBilling.getCurrentPeriod() == -1) {
                    // 本期为-1，定金
                    detail.setTradeComment("定金");
                } else if (orderBilling.getCurrentPeriod() == 0 && order.getOrderType() == 1) {
                    // 本期为0，订单为开销开单，开销单付款
                    detail.setTradeComment("开销单付款");
                } else if (orderBilling.getCurrentPeriod() == 0 && order.getOrderType() == 2) {
                    // 本期为0，订单为签订合同，首付款
                    detail.setTradeComment("首付款");
                } else if (orderBilling.getCurrentPeriod() == 1 && order.getPaymentMethod() == 0) {
                    // 本期为1，订单为全款
                    detail.setTradeComment("尾款");
                } else if (orderBilling.getCurrentPeriod() > 0 && order.getPaymentMethod() > 0) {
                    // 本期大于0，订单为分期
                    detail.setTradeComment("分期付款第" + orderBilling.getCurrentPeriod() + "期");
                }
                detailMapper.insert(detail);
            } else {
                // 不等于最后一期，收款审核通过后设置为空
                order.setPaymentApprovalFlowId(null);
                // 判断实收金额是否等于本期金额
                if (orderBilling.getFundsReceived().compareTo(orderBilling.getAmount()) == 0) {
                    // 等于
                    // 更新数据
                    LambdaUpdateWrapper<OrderBilling> orderBillingLUW = new LambdaUpdateWrapper<>();
                    orderBillingLUW.eq(OrderBilling::getId, orderBilling.getId())
                            .set(OrderBilling::getAccount, orderBilling.getAccount())
                            .set(OrderBilling::getBillStatus, orderBilling.getBillStatus())
                            .set(OrderBilling::getSalesmanCommissionId, orderBilling.getSalesmanCommissionId())
                            .set(OrderBilling::getAfterSalesCommissionId, orderBilling.getAfterSalesCommissionId());
                    orderBillingMapper.update(null, orderBillingLUW);

                    // 新增账户明细
                    IncomeExpenditureDetail detail = new IncomeExpenditureDetail();
                    // 设置账户id
                    detail.setAccountId(account.getId());
                    // 设置订单id
                    detail.setExpenseId(orderBilling.getId());
                    // 设置明细类型为收款
                    detail.setDetailType(BaseEnum.ACCOUNT_DETAIL_TYPE_COLLECTION.getCodeInt());
                    // 计算余额
                    account.setBalance(account.getBalance().add(orderBilling.getFundsReceived()));
                    // 更新账户余额
                    LambdaUpdateWrapper<Account> accountLUW = new LambdaUpdateWrapper<>();
                    accountLUW.eq(Account::getId, account.getId())
                            .set(Account::getBalance, account.getBalance());
                    accountMapper.update(null, accountLUW);
                    // 设置余额
                    detail.setBalance(account.getBalance());
                    // 设置交易时间
                    detail.setTradingHours(orderBilling.getDateReceived());
                    // 设置交易说明
                    if (orderBilling.getCurrentPeriod() == -1) {
                        // 本期为-1，定金
                        detail.setTradeComment("定金");
                    } else if (orderBilling.getCurrentPeriod() == 0 && order.getOrderType() == 1) {
                        // 本期为0，订单为开销开单，开销单付款
                        detail.setTradeComment("开销单付款");
                    } else if (orderBilling.getCurrentPeriod() == 0 && order.getOrderType() == 2) {
                        // 本期为0，订单为签订合同，首付款
                        detail.setTradeComment("首付款");
                    } else if (orderBilling.getCurrentPeriod() == 1 && order.getPaymentMethod() == 0) {
                        // 本期为1，订单为全款
                        detail.setTradeComment("尾款");
                    } else if (orderBilling.getCurrentPeriod() > 0 && order.getPaymentMethod() > 0) {
                        // 本期大于0，订单为分期
                        detail.setTradeComment("分期付款第" + orderBilling.getCurrentPeriod() + "期");
                    }
                    detailMapper.insert(detail);
                } else {
                    // 不等于
                    // 查剩余期数
                    LambdaQueryWrapper<OrderBilling> orderBillingLQW = new LambdaQueryWrapper<>();
                    orderBillingLQW.eq(OrderBilling::getOrderId, order.getId()).ne(OrderBilling::getBillStatus, 1);
                    List<OrderBilling> orderBillingList = orderBillingMapper.selectList(orderBillingLQW);
                    // 剩余金额
                    BigDecimal arrears = new BigDecimal(0);
                    for (OrderBilling o : orderBillingList) {
                        arrears = arrears.add(o.getAmount());
                    }
                    // 减去定金和首付款的剩余金额
                    BigDecimal bigDecimal = new BigDecimal(0);
                    for (OrderBilling o : orderBillingList) {
                        if (o.getCurrentPeriod() > 0) {
                            // 期数大于0的进来
                            bigDecimal = bigDecimal.add(o.getAmount());
                        }
                        if (o.getCurrentPeriod() < 1 && orderBilling.getCurrentPeriod().equals(o.getCurrentPeriod())) {
                            // 期数小于1，且期数等于本期
                            bigDecimal = bigDecimal.add(o.getAmount());
                        }
                    }
                    if (orderBilling.getFundsReceived().compareTo(arrears) == 0) {
                        // 实收金额等于剩余金额
                        // 设置收款审核通过
                        order.setPaymentApprovalFlowId(order.getPaymentApprovalFlowId());
                        // 设置当前订单为通过
                        order.setStatus(1);
                        // 本期实收等于剩余金额
                        for (OrderBilling o : orderBillingList) {
                            // 剩余期数的实收金额设置为本期金额
                            o.setFundsReceived(o.getAmount());
                            // 设置实收日期
                            o.setDateReceived(orderBilling.getDateReceived());
                            // 设置收款账户
                            o.setAccount(orderDto.getAccount());
                            // 设置账单状态
                            o.setBillStatus(1);
                            // 更新数据
                            LambdaUpdateWrapper<OrderBilling> orderBillingLUW = new LambdaUpdateWrapper<>();
                            orderBillingLUW.eq(OrderBilling::getId, o.getId())
                                    .set(OrderBilling::getFundsReceived, o.getFundsReceived())
                                    .set(OrderBilling::getDateReceived, o.getDateReceived())
                                    .set(OrderBilling::getAccount, o.getAccount())
                                    .set(OrderBilling::getBillStatus, o.getBillStatus())
                                    .set(OrderBilling::getSalesmanCommissionId, o.getSalesmanCommissionId())
                                    .set(OrderBilling::getAfterSalesCommissionId, o.getAfterSalesCommissionId());
                            orderBillingMapper.update(null, orderBillingLUW);

                            // 新增账户明细
                            IncomeExpenditureDetail detail = new IncomeExpenditureDetail();
                            // 设置账户id
                            detail.setAccountId(account.getId());
                            // 设置订单id
                            detail.setExpenseId(o.getId());
                            // 设置明细类型为收款
                            detail.setDetailType(BaseEnum.ACCOUNT_DETAIL_TYPE_COLLECTION.getCodeInt());
                            // 计算余额
                            account.setBalance(account.getBalance().add(o.getFundsReceived()));
                            // 更新账户余额
                            LambdaUpdateWrapper<Account> accountLUW = new LambdaUpdateWrapper<>();
                            accountLUW.eq(Account::getId, account.getId())
                                    .set(Account::getBalance, account.getBalance());
                            accountMapper.update(null, accountLUW);
                            // 设置余额
                            detail.setBalance(account.getBalance());
                            // 设置交易时间
                            detail.setTradingHours(o.getDateReceived());
                            // 设置交易说明
                            if (o.getCurrentPeriod() == -1) {
                                // 本期为-1，定金
                                detail.setTradeComment("定金");
                            } else if (o.getCurrentPeriod() == 0 && order.getOrderType() == 1) {
                                // 本期为0，订单为开销开单，开销单付款
                                detail.setTradeComment("开销单付款");
                            } else if (o.getCurrentPeriod() == 0 && order.getOrderType() == 2) {
                                // 本期为0，订单为签订合同，首付款
                                detail.setTradeComment("首付款");
                            } else if (o.getCurrentPeriod() == 1 && order.getPaymentMethod() == 0) {
                                // 本期为1，订单为全款
                                detail.setTradeComment("尾款");
                            } else if (o.getCurrentPeriod() > 0 && order.getPaymentMethod() > 0) {
                                // 本期大于0，订单为分期
                                detail.setTradeComment("分期付款第" + o.getCurrentPeriod() + "期");
                            }
                            detailMapper.insert(detail);
                        }
                    } else {
                        // 大于或者小于，重新计算
                        // 更新本期账单数据
                        LambdaUpdateWrapper<OrderBilling> orderBillingLUW = new LambdaUpdateWrapper<>();
                        orderBillingLUW.eq(OrderBilling::getId, orderBilling.getId())
                                .set(OrderBilling::getAccount, orderBilling.getAccount())
                                .set(OrderBilling::getBillStatus, orderBilling.getBillStatus())
                                .set(OrderBilling::getSalesmanCommissionId, orderBilling.getSalesmanCommissionId())
                                .set(OrderBilling::getAfterSalesCommissionId, orderBilling.getAfterSalesCommissionId());
                        orderBillingMapper.update(null, orderBillingLUW);

                        // 新增账户明细
                        IncomeExpenditureDetail detail = new IncomeExpenditureDetail();
                        // 设置账户id
                        detail.setAccountId(account.getId());
                        // 设置订单id
                        detail.setExpenseId(orderBilling.getId());
                        // 设置明细类型为收款
                        detail.setDetailType(BaseEnum.ACCOUNT_DETAIL_TYPE_COLLECTION.getCodeInt());
                        // 计算余额
                        account.setBalance(account.getBalance().add(orderBilling.getFundsReceived()));
                        // 更新账户余额
                        LambdaUpdateWrapper<Account> accountLUW = new LambdaUpdateWrapper<>();
                        accountLUW.eq(Account::getId, account.getId())
                                .set(Account::getBalance, account.getBalance());
                        accountMapper.update(null, accountLUW);
                        // 设置余额
                        detail.setBalance(account.getBalance());
                        // 设置交易时间
                        detail.setTradingHours(orderBilling.getDateReceived());
                        // 设置交易说明
                        if (orderBilling.getCurrentPeriod() == -1) {
                            // 本期为-1，定金
                            detail.setTradeComment("定金");
                        } else if (orderBilling.getCurrentPeriod() == 0 && order.getOrderType() == 1) {
                            // 本期为0，订单为开销开单，开销单付款
                            detail.setTradeComment("开销单付款");
                        } else if (orderBilling.getCurrentPeriod() == 0 && order.getOrderType() == 2) {
                            // 本期为0，订单为签订合同，首付款
                            detail.setTradeComment("首付款");
                        } else if (orderBilling.getCurrentPeriod() == 1 && order.getPaymentMethod() == 0) {
                            // 本期为1，订单为全款
                            detail.setTradeComment("尾款");
                        } else if (orderBilling.getCurrentPeriod() > 0 && order.getPaymentMethod() > 0) {
                            // 本期大于0，订单为分期
                            detail.setTradeComment("分期付款第" + orderBilling.getCurrentPeriod() + "期");
                        }
                        detailMapper.insert(detail);

                        // 重新计算
                        // 剩余总金额：剩余金额先减去本期实收金额
                        BigDecimal totalAmount = bigDecimal.subtract(orderBilling.getFundsReceived());
                        // 剩余期数：总期数-本期数
                        int period = 0;
                        if (orderBilling.getCurrentPeriod() > 0) {
                            // 本期期数大于0
                            period = orderBilling.getTotalPeriod() - orderBilling.getCurrentPeriod();
                        } else {
                            // 本期期数小于1，就等于总期数
                            period = orderBilling.getTotalPeriod();
                        }
                        // 每期金额，总金额除以剩余期数
                        long amount = (totalAmount.divide(BigDecimal.valueOf(period), 0, RoundingMode.DOWN))
                                .longValue();
                        // 缺失金额，总金额-(每期金额*剩余期数)
                        BigDecimal deficiency = totalAmount
                                .subtract(new BigDecimal(amount).multiply(BigDecimal.valueOf(period)));
                        // 末期金额
                        BigDecimal lastAmount = deficiency.add(new BigDecimal(amount));
                        // 更新数据，除了本期，定金和首付款
                        for (OrderBilling o : orderBillingList) {
                            if (!o.getId().equals(orderBilling.getId())) {
                                // 不等于本期
                                if (o.getCurrentPeriod() > 0) {
                                    // 不等于定金和首付款
                                    // 设置本期金额
                                    o.setAmount(new BigDecimal(amount));
                                    // 最后一期
                                    if (o.getTotalPeriod().equals(o.getCurrentPeriod())) {
                                        o.setAmount(lastAmount);
                                    }
                                    orderBillingLUW = new LambdaUpdateWrapper<>();
                                    orderBillingLUW.eq(OrderBilling::getId, o.getId())
                                            .set(OrderBilling::getAmount, o.getAmount());
                                    orderBillingMapper.update(null, orderBillingLUW);
                                }
                            }
                        }
                    }
                }
            }
        }
        LambdaUpdateWrapper<Order> orderLUW = new LambdaUpdateWrapper<>();
        orderLUW.eq(Order::getId, order.getId())
                .set(Order::getPaymentApprovalFlowId, order.getPaymentApprovalFlowId())
                .set(Order::getStatus, order.getStatus());
        orderMapper.update(null, orderLUW);
        // 创建消息通知
        String approval;
        if (orderDto.getPaymentApprovalFlowId().equals("1")) {
            // 已通过
            approval = "已通过";
        } else {
            // 未通过
            approval = "未通过";
        }
        MessageNotification msg = new MessageNotification();
        // 标题
        String title = "订单收款申请" + approval;
        msg.setTitle(title);
        // 内容
        String content = "您收款" + orderBilling.getFundsReceived() + "元的申请" + approval;
        msg.setContent(content);
        // 发布人为审核人
        msg.setPublisherId(user.getId());
        // 接收人为业务员
        msg.setReceiverId(order.getUserId());
        // 关联id
        msg.setRelevanceId(order.getId());
        // 类型为订单管理
        msg.setMsgType(5);
        // 子菜单为3订单详情
        msg.setSubmenu(3);
        // 状态为待处理
        msg.setStatus(0);
        msgNotificationMapper.insert(msg);
        return Result.success("修改成功");
    }

    @Override
    public Result changeSalesman(OrderDto orderDto) {
        if (orderDto == null || orderDto.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        Order order = orderMapper.selectById(orderDto.getId());
        if (order == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数错误");
        }
        if (orderDto.getUserId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        LambdaUpdateWrapper<Order> orderLUW = new LambdaUpdateWrapper<>();
        orderLUW.eq(Order::getId, orderDto.getId())
                .set(Order::getUserId, orderDto.getUserId());
        orderMapper.update(null, orderLUW);
        return Result.success("修改成功");
    }

    @Override
    @Transactional
    public Result changeAfterSale(OrderDto orderDto) {
        if (orderDto == null || orderDto.getId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        Order order = orderMapper.selectById(orderDto.getId());
        if (order == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数错误");
        }
        if (orderDto.getAfterSaleId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }
        User user = userMapper.selectById(orderDto.getAfterSaleId());
        if (user == null) {
            return new Result(HttpStatus.BAD_REQUEST, "参数错误");
        }
        // 设置售后员
        order.setAfterSaleId(orderDto.getAfterSaleId());
        // 更新数据
        LambdaUpdateWrapper<Order> orderLUW = new LambdaUpdateWrapper<>();
        orderLUW.eq(Order::getId, order.getId()).set(Order::getAfterSaleId, order.getAfterSaleId());
        orderMapper.update(null, orderLUW);

        // 先查询是否有该售后表
        LambdaQueryWrapper<AfterSales> afterSalesLQW = new LambdaQueryWrapper<>();
        afterSalesLQW.eq(AfterSales::getOrderId, order.getId());
        AfterSales afterSales = afterSalesMapper.selectOne(afterSalesLQW);
        if (afterSales == null) {
            // 没有则创建
            afterSales = new AfterSales();
            afterSales.setOrderId(order.getId());
            afterSales.setUserId(orderDto.getAfterSaleId());
            afterSales.setAfterSalesTime(new Date());
            afterSalesMapper.insert(afterSales);
        } else {
            // 有则修改
            afterSales.setUserId(orderDto.getAfterSaleId());
            LambdaUpdateWrapper<AfterSales> afterSalesLUW = new LambdaUpdateWrapper<>();
            afterSalesLUW.eq(AfterSales::getAfterSalesId, afterSales.getAfterSalesId())
                    .set(AfterSales::getUserId, afterSales.getUserId());
            afterSalesMapper.update(null, afterSalesLUW);
        }

        // 查询售后提成
        LambdaQueryWrapper<OrderCommission> orderCommissionLQW = new LambdaQueryWrapper<>();
        orderCommissionLQW.eq(OrderCommission::getUserId, order.getAfterSaleId());
        OrderCommission orderCommission = orderCommissionMapper.selectOne(orderCommissionLQW);

        // 查询该订单所有已收款账单
        LambdaQueryWrapper<OrderBilling> orderBillingLQW = new LambdaQueryWrapper<>();
        orderBillingLQW.eq(OrderBilling::getOrderId, order.getId()).eq(OrderBilling::getBillStatus, 1);
        List<OrderBilling> orderBillingList = orderBillingMapper.selectList(orderBillingLQW);
        if (orderBillingList.size() > 0) {
            for (OrderBilling orderBilling : orderBillingList) {
                if (orderBilling.getAfterSalesCommissionId() == null) {
                    // 账单售后提成id为空
                    // 设置售后提成id
                    orderBilling.setAfterSalesCommissionId(orderCommission.getId());
                    // 更新数据
                    LambdaUpdateWrapper<OrderBilling> orderBillingLUW = new LambdaUpdateWrapper<>();
                    orderBillingLUW.eq(OrderBilling::getId, orderBilling.getId())
                            .set(OrderBilling::getAfterSalesCommissionId, orderBilling.getAfterSalesCommissionId());
                    orderBillingMapper.update(null, orderBillingLUW);
                }
            }
        }

        // 创建消息通知
        MessageNotification msg = new MessageNotification();
        // 标题
        msg.setTitle("有新的售后派单待处理");
        // 内容
        Clients clients = clientsMapper.selectById(order.getClientsId());
        String content = "您被指派为客户(" + clients.getName() + ")订单的售后";
        msg.setContent(content);
        // 发布人为指派人
        msg.setPublisherId(StpUtil.getLoginIdAsString());
        // 接收人为售后员
        msg.setReceiverId(user.getId());
        // 关联id
        msg.setRelevanceId(afterSales.getAfterSalesId());
        // 类型为售后管理
        msg.setMsgType(7);
        // 子菜单为1售后派单
        msg.setSubmenu(1);
        // 状态为待处理
        msg.setStatus(0);
        msgNotificationMapper.insert(msg);
        return Result.success("修改成功");
    }

    @Override
    public Result orderRoyalty(RoyaltyDto royaltyDto) {
        if (royaltyDto == null || royaltyDto.getRoleId() == null) {
            return new Result(HttpStatus.BAD_REQUEST, "缺少参数");
        }

        List<RoyaltyVo> royaltyVoList = new ArrayList<>();
        SortedSet<RoyaltyVo> royaltyVos = new TreeSet<>();
        // 查询业务员或售后员
        LambdaQueryWrapper<User> userLQW = new LambdaQueryWrapper<>();
        userLQW.eq(User::getRoleId, royaltyDto.getRoleId()).eq(User::getState, BaseEnum.USER_INCUMBENCY.getCodeInt());
        List<User> userList = userMapper.selectList(userLQW);
        if (userList.size() == 0) {
            return Result.success("查询成功", royaltyVoList);
        }

        // 查提成记录
        List<String> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());
        List<OrderCommission> commissionList = orderCommissionMapper.selectBatchUserIdWithDelete(userIdList);
        // 根据userId获取OrderCommission集合
        Map<String, List<OrderCommission>> commissionMap = new HashMap<>();
        for (OrderCommission commission : commissionList) {
            if (commissionMap.containsKey(commission.getUserId())) {
                commissionMap.get(commission.getUserId()).add(commission);
            } else {
                List<OrderCommission> commissions = new ArrayList<>();
                commissions.add(commission);
                commissionMap.put(commission.getUserId(), commissions);
            }
        }

        for (User user : userList) {
            RoyaltyVo royaltyVo = new RoyaltyVo();
            royaltyVo.setUserId(user.getId());
            royaltyVo.setNickName(user.getNickName());
            royaltyVo.setUserImg(user.getImage());
            // 获取提成记录
            List<OrderCommission> orderCommissionList = commissionMap.get(user.getId());
            List<String> orderCommissionIdList = orderCommissionList.stream().map(OrderCommission::getId)
                    .collect(Collectors.toList());
            // 设置提成点
            orderCommissionList.forEach(item -> {
                if (!item.getDeleted().equals(BaseEnum.DELETED_YES.getCodeInt())) {
                    // 未删除
                    royaltyVo.setPercentage(item.getCommission());
                }
            });

            // 查询订单
            LambdaQueryWrapper<Order> orderLQW = new LambdaQueryWrapper<>();
            // 根据提成id和月份查询账单
            LambdaQueryWrapper<OrderBilling> orderBillingLQW = new LambdaQueryWrapper<>();
            // 判断为业务员还是售后员
            if (royaltyDto.getRoleId() == 7) {
                // 售后员按自己用户id查询
                orderLQW.eq(Order::getAfterSaleId, user.getId());
                orderBillingLQW.in(OrderBilling::getAfterSalesCommissionId, orderCommissionIdList);
            } else {
                // 业务员按自己用户id查询
                orderLQW.eq(Order::getUserId, user.getId());
                orderBillingLQW.in(OrderBilling::getSalesmanCommissionId, orderCommissionIdList);
            }
            // 按时间
            if (royaltyDto.getYear() != null) {
                orderLQW.apply("YEAR(create_time) = {0}", royaltyDto.getYear());
                orderBillingLQW.apply("YEAR(date_received) = {0}", royaltyDto.getYear());
            } else if (royaltyDto.getYearMonth() != null) {
                orderLQW.apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", royaltyDto.getYearMonth());
                orderBillingLQW.apply("DATE_FORMAT(date_received, '%Y-%m') = {0}", royaltyDto.getYearMonth());
            } else {
                // 默认为本月
                orderLQW.apply("DATE_FORMAT(create_time, '%Y-%m') = {0}", YearMonth.now());
                orderBillingLQW.apply("DATE_FORMAT(date_received, '%Y-%m') = {0}", YearMonth.now());
            }
            List<Order> orderList = orderMapper.selectList(orderLQW);
            royaltyVo.setTotal(orderList.size());
            // 计算销售金额
            BigDecimal salesAmount = new BigDecimal(0);
            if (orderList.size() != 0) {
                for (Order order : orderList) {
                    salesAmount = salesAmount.add(order.getTransactionAmount());
                }
            }
            royaltyVo.setSalesAmount(salesAmount);
            // 回款金额
            BigDecimal collectionAmount = new BigDecimal(0);
            // 发放金额
            BigDecimal totalAmount = new BigDecimal(0);
            // 根据提成id和月份查询账单
            List<OrderBilling> orderBillingList = orderBillingMapper.selectList(orderBillingLQW);
            if (orderBillingList.size() != 0) {

                for (OrderBilling orderBilling : orderBillingList) {
                    collectionAmount = collectionAmount.add(orderBilling.getFundsReceived());
                }
                totalAmount = collectionAmount.multiply(new BigDecimal(String.valueOf(royaltyVo.getPercentage())));
            }
            royaltyVo.setCollectionAmount(collectionAmount);
            royaltyVo.setTotalAmount(totalAmount);
            royaltyVos.add(royaltyVo);
        }
        royaltyVoList.addAll(royaltyVos);
        for (int i = 0; i < royaltyVoList.size(); i++) {
            royaltyVoList.get(i).setRanking(i + 1);
        }
        // System.out.println("royaltyVoList=>"+royaltyVoList);
        return Result.success("查询成功", royaltyVoList);
    }

    @Override
    public Result getReminderDays() {
        Current current = currentMapper.selectById("3");
        return Result.success("查询成功", current);
    }

    @Override
    public Result updateReminderDays(Current current) {
        current.setId("3");
        currentMapper.updateById(current);
        return Result.success("修改成功");
    }
}
